from common import BaseRequestHandler
from lib.common_cards import random, NUMBER_OF_RANKS, NUMBER_OF_SUITS
from lib.dbobjects import Profiler

from datetime import datetime

from google.appengine.api.users import User
from google.appengine.api import users

_WINNING_FACTOR = 10

class Level1Page(BaseRequestHandler):
    
    def get(self):
        if (users.is_current_user_admin()):
            self.redirect('/admin')
        else:
            information = "This is an old Russian game. " + \
                    "You have to guess the rank of the card. " + \
                    "If you are successful you get TEN times " + \
                    "as much as you bid (plus your bet also " + \
                    "gets returned).  To play just click on " + \
                    "the card of your choice. REMEMBER: The " + \
                    "suit doesn't matter. The game is inspired" + \
                    " by the Russian book THE QUEEN OF SPADES" + \
                    " by Alexander Pushkin where the main" + \
                    " character plays this game."
                    
            self.display(information=information)
    
    def post(self):
        # Look up profiler info and read the form values
        profilers_query = Profiler.all().filter("user =", 
                users.get_current_user()).order('-modified')
        profiler = profilers_query.get()
        
        bet = int(self.request.get('bet'))
        
        # If somehow the bet was bigger than the money, go home
        if profiler.money < self.LEVEL1_CUTOFF or bet > profiler.money:
            self.redirect('/')
        else:
            casino_query = Profiler.all().filter("user =",
                    User("Casino")).order('-modified')
            casino = casino_query.get()
            if casino is None:
                casino = Profiler(user = User("Casino"),
                        nickname = "Robert De Niro", money = 0)
            # Read the hidden values from the template
            guess = int(self.request.get('guess'))
            suit = int(self.request.get('suit'))
            # Generate the card and see the results
            generated_card = random.randint(0, NUMBER_OF_RANKS-1)
            result_images = []
            result_messages = []
            new_bet = bet
            if guess == generated_card:
                payoff = bet * _WINNING_FACTOR
                won = True
                result_messages.append("Congratulations!" + 
                        "  You have guessed my card correctly: ")
                result_images.append("/images/card_" + 
                        str(suit * NUMBER_OF_RANKS + guess) + ".png")
                result_messages.append("Since you bid " + str(bet) + 
                        " you have just WON " + str(payoff) + " extra!")
            else:
                payoff = bet * -1
                won = False
                result_messages.append("You picked: ")
                result_images.append("/images/card_" +
                        str(suit * NUMBER_OF_RANKS + guess) + ".png")
                result_messages.append(" my card was: ")
                result_images.append("/images/card_" +
                        str(suit * NUMBER_OF_RANKS + generated_card) + ".png")
                result_messages.append("You have lost your bet of " +
                        str(bet))
                if profiler.money < 2 * bet:
                    new_bet = profiler.money - bet
            
            profiler.money += payoff
            casino.money -= payoff   
            profiler.modified = datetime.now()
            profiler.hands_per_level[0] += 1
            casino.put()
            profiler.put()
            
            if profiler.money < 1:
                self.redirect('/')
            else:
                # Put everything we want to put into template_values
                template_values = {'new_bet': new_bet,
                                   'won': won,
                                   'result_messages': result_messages,
                                   'result_images': result_images}
                self.display(template_values)
        
    def display(self, passed_template_values=[], information=None):
        profilers_query = Profiler.all().filter("user =",
                users.get_current_user()).order('-modified')
        profiler = profilers_query.get()
        # Prepare the next round
        clickable_images = []
        suitID = random.randint(0, NUMBER_OF_SUITS - 1)
        for i in xrange(NUMBER_OF_RANKS):
            cardID = suitID * NUMBER_OF_RANKS + i
            clickable_images.append("/images/card_" + str(cardID) + ".png")
        template_values = {'level_name': self.LEVEL1_NAME,
                           'profiler': profiler,
                           'clickable_images': clickable_images,
                           'suit': suitID}
        if information is not None and profiler.hands_per_level[0] < 10:
            template_values['information'] = information
        template_values.update(passed_template_values)
        self.generate('level1.html', template_values)